package com.rongzhe.house.ui.activity;

import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.rongzhe.house.R;
import com.rongzhe.house.entity.Dictionary;
import com.rongzhe.house.entity.voo.HouseConfig;
import com.rongzhe.house.entity.voo.HouseDetail;
import com.rongzhe.house.entity.voo.HouseTraffic;
import com.rongzhe.house.manager.DictionaryManager;
import com.rongzhe.house.presenter.HouseInfoPresenter;
import com.rongzhe.house.ui.view.BannerView;
import com.rongzhe.house.ui.view.FolderTextView;
import com.rongzhe.house.ui.view.NoScrollListview;
import com.rongzhe.house.ui.view.NotifyingScrollView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by huang on 2017/11/19.
 */

public class HouseInfoActivity extends BaseActivity<HouseInfoPresenter> {
    public static final String EXTRA_HOUSE_ID = "extra_house_id";
    @BindView(R.id.text_house_area)
    TextView textHouseArea;
    @BindView(R.id.text_hous_desc)
    TextView textHousDesc;
    @BindView(R.id.text_price)
    TextView textPrice;
    @BindView(R.id.text_rent_rule)
    TextView textRentRule;
    @BindView(R.id.house_measure_of_area)
    TextView houseMeasureOfArea;
    @BindView(R.id.house_type)
    TextView houseType;
    @BindView(R.id.house_floor)
    TextView houseFloor;
    @BindView(R.id.house_orientation)
    TextView houseOrientation;
    @BindView(R.id.container1)
    LinearLayout container1;
    @BindView(R.id.text_house_address)
    TextView textHouseAddress;
    @BindView(R.id.text_house_configure)
    TextView textHouseConfigure;
    @BindView(R.id.container2)
    LinearLayout container2;
    @BindView(R.id.text_house_description)
    TextView textHouseDescription;
    @BindView(R.id.text_house_description_detail)
    FolderTextView textHouseDescriptionDetail;
    @BindView(R.id.text_house_info)
    TextView textHouseInfo;
    @BindView(R.id.list_house_info)
    NoScrollListview listHouseInfo;
    @BindView(R.id.bannerView)
    BannerView bannerView;
    @BindView(R.id.container_other_room)
    LinearLayout containerOtherRoom;
    @BindView(R.id.container_traffic_info)
    LinearLayout containerTrafficInfo;
    @BindView(R.id.scroller)
    NotifyingScrollView scroller;
    @BindView(R.id.mapview_traffic)
    ImageView mapviewTraffic;
    @BindView(R.id.mapview)
    MapView mapview;
    @BindView(R.id.btn_booking_house)
    Button btnBookingHouse;
    @BindView(R.id.btn_order_now)
    Button btnOrderNow;
    private CheckBox mCheckboxCollection;
    private Drawable mActionBarDrawable;

    private boolean mStared = false;
    private List<String> HOUSE_CONFIG_LIST = new ArrayList<>();

    {
        HOUSE_CONFIG_LIST.add("bed");
        HOUSE_CONFIG_LIST.add("wardrobe");
        HOUSE_CONFIG_LIST.add("desk");
        HOUSE_CONFIG_LIST.add("wifi");
        HOUSE_CONFIG_LIST.add("washwheel");
        HOUSE_CONFIG_LIST.add("heater");
        HOUSE_CONFIG_LIST.add("airCondition");
        HOUSE_CONFIG_LIST.add("microwaveOven");
    }

    @Override
    protected HouseInfoPresenter createPresenter() {
        return new HouseInfoPresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_info);
        ButterKnife.bind(this);
        mActionBarDrawable = new ColorDrawable(getResources().getColor(R.color.white_bg));
//        scroller.setOnScrollChangedListener(new NotifyingScrollView.OnScrollChangedListener() {
//            @Override
//            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
//                int hight = bannerView.getHeight();
//                int alpha;
//                if (t < hight) {
//                    alpha = 0;
//                } else {
//                    alpha = 255;
//                }
//                mActionBarDrawable.setAlpha(alpha);
//                getSupportActionBar().setBackgroundDrawable(mActionBarDrawable);
//            }
//        });
        mBaiduMap = mapview.getMap();
    }

    private BaiduMap mBaiduMap;

    @Override
    protected void configActionBar() {
        getSupportActionBar().show();
        getSupportActionBar().setCustomView(R.layout.action_bar_house_detail);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(
                getResources().getColor(android.R.color.transparent)));
        //去除actionbar兩邊的padding
        Toolbar parent = (Toolbar) getSupportActionBar().getCustomView().getParent();
        parent.setContentInsetsAbsolute(0, 0);
        mCheckboxCollection = (CheckBox) getSupportActionBar().getCustomView()
                .findViewById(R.id.checked_collection);
        mCheckboxCollection.setOnClickListener(mCollectionClickListener);
        getSupportActionBar().getCustomView().findViewById(R.id.btn_back)
                .setOnClickListener(mBackClickListener);
        getSupportActionBar().getCustomView().findViewById(R.id.btn_share)
                .setOnClickListener(mShareClickListener);
        //去除actionbar兩邊的padding
    }

    private View.OnClickListener mShareClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    };

    private View.OnClickListener mBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    };

    private void onShareClick() {
        //TODO
    }


    public void setData(final HouseDetail houseDetail) {
        List<BannerView.BannerData> bannerDatas = new ArrayList<>();
        if (houseDetail.getHouseImageList() != null && houseDetail.getHouseImageList().size() > 0) {
            for (int i = 0; i < houseDetail.getHouseImageList().size(); i++) {
                bannerDatas.add(new BannerView.BannerData(-1,
                        houseDetail.getHouseImageList().get(i).getUrl(), null));
            }
        } else {
            //TODO add the no image
            bannerDatas.add(new BannerView.BannerData(R.mipmap.welcom, null, null));
        }
        bannerView.setDatas(bannerDatas);
        textHouseArea.setText(houseDetail.getName());
        textHousDesc.setText(houseDetail.getType());
        textPrice.setText(houseDetail.getRent() + "元/月");
        houseMeasureOfArea.setText(houseDetail.getArea() + "㎡");
        houseType.setText(houseDetail.getType());
        textHouseDescriptionDetail.setText(houseDetail.getPeriphery());
        if (houseDetail.getFloor() != null && houseDetail.getTotalFloor() != null){
            houseFloor.setText(houseDetail.getFloor() + "/" + houseDetail.getTotalFloor() + "层");
        }
        if (houseDetail.getOrientation() != null) {
            houseOrientation.setText(DictionaryManager.getInstance().pareItem(
                    Dictionary.Companion.getHOUSE_ORIENTATION(), houseDetail.getOrientation()));
        }
        //整租
        if (houseDetail.getEntireRent()) {
            containerOtherRoom.setVisibility(View.GONE);
        } else {
            //TODO list room info
            containerOtherRoom.setVisibility(View.VISIBLE);
        }
        //交通信息
        if (houseDetail.getHouseTrafficList() != null) {
            containerTrafficInfo.removeAllViews();
            for (HouseTraffic houseTraffic : houseDetail.getHouseTrafficList()) {
                TextView item = (TextView) getLayoutInflater().inflate(
                        R.layout.list_item_text_traffic, containerTrafficInfo, false);
                item.setText(houseTraffic.getTraffic());
                containerTrafficInfo.addView(item);
            }
        }
        if (houseDetail.getHouseTrafficList() != null
                && houseDetail.getHouseTrafficList().size() > 0) {
            HouseTraffic houseTraffic = houseDetail.getHouseTrafficList().get(0);
            textHouseAddress.setText(houseTraffic.getTraffic());
        }
        if (houseDetail.getHouseConfig() != null) {
            HouseConfig houseConfig = houseDetail.getHouseConfig();
            Field fields[] = HouseConfig.class.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field filed = fields[i];
                int configIndex = HOUSE_CONFIG_LIST.indexOf(filed.getName());
                if (configIndex != -1) {
                    filed.setAccessible(true);
                    try {
                        byte data = (byte) filed.get(houseConfig);
                        if (data >= 1) {
                            container2.getChildAt(configIndex).setVisibility(View.VISIBLE);
                        } else {
                            container2.getChildAt(configIndex).setVisibility(View.GONE);
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (houseDetail.getCanCollection() != null && houseDetail.getCanCollection()) {
            mStared = false;
        } else {
            mStared = true;
        }
        updateCollectionState();
        if (houseDetail.getLatitude() != null && houseDetail.getLongitude() != null) {
            mapviewTraffic.setVisibility(View.VISIBLE);
            Message message = mHandler.obtainMessage(MSG_UPDATE_BAIDUMAP_CENTER);
            message.obj = houseDetail;
            mHandler.sendMessage(message);
        } else {
            mapviewTraffic.setVisibility(View.GONE);
        }
        //如果房子是已出租, 将button状态改变
        if (houseDetail.getRentStatus() != null && houseDetail.getRentStatus() == 2) {
            btnBookingHouse.setEnabled(false);
            btnOrderNow.setEnabled(false);
            btnOrderNow.setText(getString(R.string.house_rented));
        }
    }

    private static final int MSG_UPDATE_BAIDUMAP_CENTER = 1;
    private static final int SNAPSHOT_SCOP = 2;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_BAIDUMAP_CENTER:
                    HouseDetail houseDetail = (HouseDetail) msg.obj;
                    LatLng latLng = new LatLng(houseDetail.getLatitude(), houseDetail.getLongitude());
                    MapStatus mapStatus = new MapStatus.Builder()
                            .target(latLng)
                            .zoom(16)
                            .build();
                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                    mBaiduMap.setMapStatus(mapStatusUpdate);
                    sendEmptyMessageDelayed(SNAPSHOT_SCOP, 4 * 1000);
                    break;
                case SNAPSHOT_SCOP:
                    mBaiduMap.snapshotScope(null, new BaiduMap.SnapshotReadyCallback() {
                        @Override
                        public void onSnapshotReady(Bitmap bitmap) {
                            mapviewTraffic.setImageBitmap(bitmap);
                            mapview.setVisibility(View.GONE);
                        }
                    });
                    break;
            }
        }
    };

    private void updateCollectionState() {
        mCheckboxCollection.setChecked(mStared);
    }

    @OnClick(R.id.btn_booking_house)
    public void onLookingHouseClick() {
        mPresenter.onLookingHouseClick();
    }

    @OnClick(R.id.btn_order_now)
    public void onOrderNowClick() {
        mPresenter.orderCreate();
    }

    private View.OnClickListener mCollectionClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPresenter.changeStarState();
        }
    };

    public void onStarChanged() {
        mStared = !mStared;
        updateCollectionState();
    }
}
